
/**  */

const db = require('db');
const getAccessToken = require('tools/dd/getAccessToken');
const getUserInfo = require('tools/dd/getUserInfo');
const { toUpdate } = require('tools/sqlString');

module.exports = async ctx => {
    const { connection, run } = db.init();
    await run('BEGIN'); // 开始事务
    try {
        const body = ctx.request.body;
        const id = body.id;
        const company = ctx.headers["company-id"];
        const access_token = await getAccessToken(company);
        const user = await getUserInfo(access_token, body.pmId);
        await update(id, body, user, run);
        await run('COMMIT');
        ctx.status = 200;
        ctx.body = '{}';
    } catch (error) {
        await run('ROLLBACK');
        ctx.status = 500;
        ctx.body = error;
    }
    connection.end();
}

async function update(id, body, user, run) {
    const sql = toSqlString(id, body, user);
    const result = await run(sql);
    if (result.err) {
        throw result.err;
    }
}

function toSqlString(id, body, user) {
    const sql = `
        UPDATE orders SET ${toUpdate({ ...body, orderStatus: '4', pmEmail: user.email || 'null' })}
        WHERE id = ${id}
    `;
    return sql;
}